import {
	base64_encode,
	base64_decode
} from "@/common/tools/base64.js";
import md5 from '@/common/tools/md5.js';
import _ from "underscore"; 
import { object } from "../../uni_modules/uview-plus/libs/function/test.js";
import {usePageStore} from "./store.js"
import {cache,Toast} from "./uniApi.js";
 
var util = {}
 
util.debug = false; //关闭显示false console

util.base64Encode = function(str) {
	return base64_encode(str)
};

util.base64Decode = function(str) {
	return base64_decode(str)
};

util.md5 = function(str) {
	return md5(str)
};
//把价格对象转换成数组对象{}
util.o2a = (o)=>{
	return _.map( o ,(i,v )=> {
			return {name: v , value: i, checked:false}						
	})
}

/**
	构造微擎地址, 
	@params action 微擎系统中的controller, action, do，格式为 'wxapp/home/navs'
	@params querystring 格式为 {参数名1 : 值1, 参数名2 : 值2}
*/
util.url = function(action, querystring) {
	var url = "&m=kbwdl_nickscenery&";
	if (action) {
		action = action.split('/');
		if (action[0]) {
			url += 'c=' + action[0] + '&';
		}
		if (action[1]) {
			url += 'a=' + action[1] + '&';
		}
		if (action[2]) {
			url += 'do=' + action[2] + '&';
		}
	}
	if (querystring && typeof querystring === 'object') {
		for (let param in querystring) {
			if (param && querystring.hasOwnProperty(param) && querystring[param]) {
				url += param + '=' + querystring[param] + '&';
			}
		}
	}
	return url;
}

function getQuery(url) {
	var theRequest = [];
	if (url.indexOf("?") != -1) {
		var str = url.split('?')[1];
		var strs = str.split("&");
		for (var i = 0; i < strs.length; i++) {
			if (strs[i].split("=")[0] && unescape(strs[i].split("=")[1])) {
				theRequest[i] = {
					'name': strs[i].split("=")[0],
					'value': unescape(strs[i].split("=")[1])
				}
			}
		}
	}
	return theRequest;
}
/*
 * 获取链接某个参数
 * url 链接地址
 * name 参数名称
 */
function getUrlParam(url, name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象  
	var r = url.split('?')[1].match(reg); //匹配目标参数  
	if (r != null) return unescape(r[2]);
	return null; //返回参数值  
}
/**
 * 获取签名 将链接地址的所有参数按字母排序后拼接加上token进行md5
 * url 链接地址
 * date 参数{参数名1 : 值1, 参数名2 : 值2} *
 * token 签名token 非必须
 */
function getSign(url, data, token) {
	token = '&kbwdl_nickscenerytoken990';
	var querystring = '';
	var sign = getUrlParam(url, 'sign');
	if (sign || (data && data.sign)) {
		return false;
	} else {
		if (url) {
			querystring = getQuery(url);
		}
		if (data) {
			var theRequest = [];
			for (let param in data) {
				if (param && data[param]) {
					theRequest = theRequest.concat({
						'name': param,
						'value': data[param]
					})
				}
			}
			querystring = querystring.concat(theRequest);
		}
		//排序
		querystring = _.sortBy(querystring, 'name');
		//去重
		querystring = _.uniq(querystring, true, 'name');
		var urlData = '';
		for (let i = 0; i < querystring.length; i++) {
			if (querystring[i] && querystring[i].name && querystring[i].value) {
				urlData += querystring[i].name + '=' + querystring[i].value;
				if (i < (querystring.length - 1)) {
					urlData += '&';
				}
			}
		}
		token = token ? token : '';
		sign = md5(urlData + token);
		return sign;
	}
}
util.getSign = function(url, data, token) {
	return getSign(url, data, token);
};

function HostUri() {
	const ee = usePageStore();
	return ee.HostUri
	//return siteinfo.siteroot + "?i="+siteinfo.uniacid+"&t="+siteinfo.multiid+"&v="+siteinfo.version+"&from=wxapp";
}
//获取微信支付url
function getWxpayUrl(){
	var url = HostUri() + util.url("entry/wxapp", {do:'pay' });
	// #ifdef MP-WEIXIN
	var sessionid = uni.getStorageSync('userInfo').sessionid;
	var state = getUrlParam(url, 'state');
	if (!state) {
		if (sessionid)
			url = url + 'state=we7sid-' + sessionid + '&';
		else
			url = url + 'state=we7sid-' + '&';
	}
	// #endif
	return url + "sign=" + getSign(url);
}
util.getWxpayUrl = getWxpayUrl;

function getModuleUrl(acdo, op, params) {	 
	var url = HostUri() + util.url("entry/wxapp", {do:'index', s: acdo + "/"+op });
	// var sessionid = window.siteInfo?.session_id || '6ce3e31d001ca82be9f2a9582eac8d31';
	// #ifdef MP-WEIXIN
    url = HostUri() + util.url("entry/wxapp", { do:'index', s: acdo + "/"+op });
	var sessionid = uni.getStorageSync('userInfo').sessionid;	
	var state = getUrlParam(url, 'state');
	if (!state) {
		if (sessionid)
			url = url + 'state=we7sid-' + sessionid + '&';
		else
			url = url + 'state=we7sid-' + '&';
	}
	// #endif
	

	const sign = getSign(url);

	return url + "sign=" + sign;
	//https://api.siyueweb.cn/app/index.php?i=19&t=19&v=1.8.1&
	//from=wxapp&c=entry&a=wxapp&do=enset&
	//state=we7sid-4e2e885f16f647b401358b7cfe68d61f&
	//m=kbquke_house&sign=dc25975c07be45d98d111bba55a18dc2&op=adinfo
}
util.getModuleUrl = getModuleUrl;

function getWe7Url(uri, queryString) {
	var url = HostUri() + util.url(uri, queryString);
	var sessionid = uni.getStorageSync('userInfo').sessionid;
	// #ifdef MP-WEIXIN
	var state = getUrlParam(url, 'state');
	if (!state && sessionid) {
		url = url + 'state=we7sid-' + sessionid + '&';
	}
	// #endif
	
	const sign = getSign(url);
	return url + "sign=" + sign;
}

function sendPost(url, data){
	// #ifdef MP-WEIXIN
	return wxapp_SendPost(url, data);
	// #endif
	// #ifdef H5
	return gzh_SendPost(url, data);
	// #endif
}

function gzh_SendPost(url, data = {}) {
	let apiToken =  cache.get('apiToken');
	let option = {
		url: url,
		method: "POST",
		header: {
			'x-requested-with': 'xmlhttprequest',
			'Content-Type': 'application/x-www-form-urlencoded',
			'Authorization': "Bearer " + apiToken,
			//'content-type': 'application/json; charset=utf-8'  ,
		}
	};
	const ee = usePageStore();
	//方便测试加入openid
	data = Object.assign(data,{openid: ee.siteinfoJs?.openid|| ''})
	if (data) { 		
		option.data = data;
	}
	util.console('发送request：', option)

	return new Promise((resolve, reject) => {
		uni.request(option).then(ret => {
			util.console('uni.request success =>' ,ret)
			uni.hideLoading();
			 // console.log("返回结果：", ret)
			if (ret.statusCode == 200) {
				if (ret.data.errno == 0) {
					resolve(ret.data.data);
				} else if(ret.data.errno ==  1 ){
						Toast(ret.data.message) ;
						resolve(ret.data)
				}else if(ret.data.errno ==  199 ){
						Toast(ret.data.message) ;
						reject(ret.data)
				}else if(ret.data.errno == 401){
					uni.navigateTo({
						url:"/pages/login/login"
					})
					reject(ret.data)
				
				} else if(ret.data?.type =='info'){
					Toast(ret.data.message) ;
					 
					reject(ret.data)
				} else {
					Toast('服务错误') ;
					 
					reject(ret.data)
				}
			
			
			} else {
				Toast('服务返回失败')
				reject(ret)
			}
		}, (fail)=> reject(fail))
	})
}

function wxapp_SendPost(url, data) {
	let apiToken =  cache.get('apiToken');
	var option = {
		url: url,
		method: "POST",
		header: {
			'x-requested-with': 'xmlhttprequest',
			'Content-Type': 'application/x-www-form-urlencoded',
			'Authorization': "Bearer " + apiToken,
			//'content-type': 'application/json; charset=utf-8'  ,
		}
	};
	if (data) {
		option.data = data;
	}
	//util.console('发送request：', option)

	return new Promise((resolve, reject) => {
		uni.request(option).then(ret => {
			 util.console("返回结果：", ret)
			if (ret.statusCode == 200) {
				if (ret.data.errno == 0) {
					resolve(ret.data.data);
				} else if (ret.data.errno == '41009') {
					uni.setStorageSync('userInfo', '');
					util.getWxappUserInfo(function(userInfo) {
						//加入sessionid重新执行  
						if (userInfo.sessionid) {
							option.url = option.url + '&state=we7sid-' + userInfo.sessionid + '&';
							return sendPost(option.url, option.data).then(
								ret => resolve(ret)
							);
						}
					});
				}else if(ret.data.errno == 401){
					uni.navigateTo({
						url:"/pages/login/login"
					})
					reject(ret)
				}else if(ret.data.errno ==  199 ){
						Toast(ret.data.message) ;
						reject(ret.data)  	 
				}else if(ret.data.errno == '1'){
					Toast(ret.data.message) ;
					reject(ret.data)
				}else if(ret?.type =='info'){
				   Toast(ret.data.message) ;
					reject(ret.data)
				} else {
					resolve(ret.data)
				}
			} else {
				reject(ret)
			}
		})
	})
}

util.register = function(username, password, repassword) {
	return sendPost(getWe7Url('auth/register/register'), {
		username,
		password,
		repassword
	})
}
util.login = function(form) {
	return sendPost(getWe7Url('auth/login/basic'), {
		...form,
		mode: 'basic'
	})
}

/*
 * 获取用户信息
 */
util.getWxappUserInfo = function(cb, wxInfo) {
	var login = function() {

		var userInfo = {
			'sessionid': '',
			'wxInfo': '',
			'memberInfo': '',
		};
		wx.login({
			success: function(res) {

				util.getWe7User(function(userInfo) {

					if (wx.canIUse('getUserInfo')) {
						// 如果可用
						wx.getUserInfo({
							withCredentials: true,
							success: function(wxInfo) {
								util.upadteUser(wxInfo, function(userInfo) {
									typeof cb == "function" && cb(
										userInfo);
								})
							},
							fail: function() {
								typeof cb == "function" && cb(userInfo);
							}
						})
					} else {
						typeof cb == "function" && cb(userInfo);
					}

				}, res.code)
			},
			fail: function() {
				wx.showModal({
					title: '获取信息失败',
					content: '请允许授权以便为您提供给服务',
					success: function(res) {
						if (res.confirm) {
							// util.getWxappUserInfo();
						}
					}
				})
			}
		});
	};

	var userInfo = wx.getStorageSync('userInfo') || {};
	if (userInfo.sessionid) {
		util.checkSession({
			success: function() {
				if (wxInfo) {
					util.upadteUser(wxInfo, function(userInfo) {
						typeof cb == "function" && cb(userInfo);
					})
				} else {
					typeof cb == "function" && cb(userInfo);
				}
			},
			fail: function() {
				userInfo.sessionid = '';

				uni.removeStorageSync('userInfo');
				login();
			}
		})
	} else {
		//调用登录接口
		login();
	}
}

util.getWe7User = function(cb, code) {

	var userInfo = uni.getStorageSync('userInfo') || {};
	sendPost(getWe7Url("auth/session/openid", {
		code: code ? code : ''
	})).then(session => {

		if (session.sessionid) {
			userInfo.sessionid = session.sessionid
			userInfo.memberInfo = session.userinfo
			uni.setStorageSync('userInfo', userInfo)
		}
		typeof cb == "function" && cb(userInfo);
	})

}

util.upadteUser = function(wxInfo, cb) {

	var userInfo = uni.getStorageSync('userInfo') || {};
	if (!wxInfo) {
		return typeof cb == "function" && cb(userInfo);;
	}
	userInfo.wxInfo = wxInfo.userInfo;

	// wx.setStorageSync('userInfo', userInfo);
	sendPost(
		getWe7Url("auth/session/userinfo"), {
			signature: wxInfo.signature,
			rawData: wxInfo.rawData,
			iv: wxInfo.iv,
			encryptedData: wxInfo.encryptedData
		}).then((res) => {
		if (!res.errno) {
			userInfo.memberInfo = res.data;
			uni.setStorageSync('userInfo', userInfo);
		}
		typeof cb == "function" && cb(userInfo);
	})


}
util.checkSession = function(option) {
	sendPost(getWe7Url('auth/session/check'))
		.then((res) => {
			if (!res.data.errno) {
				typeof option.success == "function" && option.success();
			} else {
				typeof option.fail == "function" && option.fail();
			}
		}).catch(e => {
			typeof option.fail == "function" && option.fail();
		})
}
util.console = function(info, data) {
	if (util.debug) {
		console.log(info, data)

	}
}
//接口获取配置参数
util.getSiteInfo = () => {
	return sendPost(getModuleUrl('webfront', 'config'));
}
util.getEnsetAdinfo = function() {
	return sendPost(getModuleUrl('enset', 'adinfo'));
}

util.sendPost= sendPost;
//获取首页导航

util.getNavMenus = function() {
	return sendPost(getModuleUrl('enset', 'navmenu'));
}

util.getSechouseList = function( param ) {
	return sendPost(getModuleUrl('house', 'sechouse'),  param);
}

util.getModuleData = function(modelAction,param){
	var m = modelAction.split('/');	
	return sendPost(getModuleUrl( m[0], m[1]),  param);
}


util.pointToMarker= function(point, i, joinCluster = true)
{
	const ee = usePageStore();
	var extend = ()=>{
	 if(!joinCluster) 
		return {};// {clusterId: i +1}
	else 
		return {joinCluster: joinCluster}
	}  
	return Object.assign({},  {
	id: i +1,
	width: 12,
	height: 12, 		
	latitude:  point.latitude,
	longitude: point.longitude, 	
	iconPath: ee.webUrl + '/public/images/location2.png',  
	 // 指定了该参数才会参与聚合
		label:{
			content: point.title,
			color: '#fff', 			 
			borderWidth: '5',
			borderColor: '#2E9EEE',
			borderRadius: '6',
			bgColor:  '#2E9EEE',
			padding: 5,
			ariaLabel: point.title,
			x: '-24', //H5
			y:'-39',
			anchorX: '-24', //小程序
			anchorY: '-39',
		}
	} , extend()); 
}


export default util;